from fastapi import APIRouter

from app.models.location import Province, City
from app.schemas.location import AddressUpdateRequest
from app.core.config import settings
from app.services.scheduler.scheduler import update_radiation_data

router = APIRouter()

@router.get(
    "/provinces-with-cities",
    summary="获取所有省份及其下属城市",
    description="返回所有省份列表，每个省份中包含对应的城市列表，用于前端省市级联选择。"
)
async def get_provinces_with_cities():

    provinces = await Province.all()
    cities = await City.all()

    # 建立城市的映射表：{province_id: [city, city, ...]}
    city_map = {}
    for city in cities:
        city_map.setdefault(city.province_id, []).append(city)

    result = []
    for province in provinces:
        result.append({
            "id": province.id,
            "name_cn": province.name_cn,
            "cities": [
                {"id": city.id, "name_cn": city.name_cn}
                for city in city_map.get(province.id, [])
            ]
        })

    return result

@router.post(
    "/update",
    summary="更新设置中的地址",
    description="根据前端传入的省份ID和城市ID，更新配置中的地址信息。"
)
async def update_setting_address(data: AddressUpdateRequest):
    province_id = data.province_id
    city_id = data.city_id
    province = await Province.get_or_none(id=province_id)

    if not province:
        raise ValueError("省份不存在")
    city = await City.get_or_none(id=city_id)
    if not city:
        raise ValueError("城市不存在")

    await settings.set_location(province.name_cn, city.name_cn)

    await update_radiation_data()

    return {"message": f"成功设置地址为 {province.name_cn}-{city.name_cn}"}